import Vue from 'vue';
// import api from '../api';
import Vuex from 'vuex';
Vue.use(Vuex);
import _ from 'underscore'

import vuexI18n from 'vuex-i18n'
import moment from "moment";
const store = new Vuex.Store({
  modules: {
    i18n: vuexI18n.store
  }
})

store.registerModule('vux', {
  state: {

    demoScrollTop: 0,
    isLoading: false,
    direction: 'forward',
    guidelist: [],
    guideShow: false,
    isLogin: false,
    title: "",
    sid: "", // websocket id  暂时未用到.
    wsLogin: false,
    socketOpen: false, //控制是否建立socket链接
    username: "???",
    username: "???",
    uid: (JSON.parse(localStorage.getItem('timeUserInfo')) && JSON.parse(localStorage.getItem('timeUserInfo')).uid) || 0,
    openid: "",
    userinfo: null, //app使用,登录后赋值.
    isloginApp: false,
    amount: 0, //金钱
    headimg: "" //用户头像
  },
  mutations: {
    title(state, payload) {
      state.title = payload.title;
    },
    login(state, payload) {
      state.isLogin = payload.value || false; //默认false
      console.log("mutations login:" + state.isLogin);
    },
    updateDemoPosition(state, payload) {
      state.demoScrollTop = payload.top
    },
    updateLoadingStatus(state, payload) {
      state.isLoading = payload.isLoading
    },
    updateDirection(state, payload) {
      state.direction = payload.direction
    },
    updateGuide(state, payload) {
      state.guidelist = payload.guidelist;
      state.guideShow = payload.guideShow;
    },
    updateGuideShow(state, payload) {
      state.guideShow = payload.guideShow;
    },
    openid(state, payload) {
      state.openid = payload.openid
    },
    username(state, payload) {
      state.username = payload.username
    },
    sid(state, payload) {
      state.sid = payload.sid;
    },
    wsLogin(state, payload) {
      state.wsLogin = payload.wsLogin;
    },
    uid(state, payload) {
      if (payload.uid) {
        state.uid = payload.uid
      } else {
        state.uid = (JSON.parse(localStorage.getItem('timeUserInfo')) && JSON.parse(localStorage.getItem('timeUserInfo')).uid) || ''
      }
    },
    amount(state, payload) {
      state.amount = payload.tscore;
    },
    headimg(state, payload) {
      state.headimg = payload.headimg
    },
    user(state, payload) {
      state.headimg = payload.headimg || payload.headimgurl || ""
      state.amount = payload.tscore || 0
      state.uid = payload.uid || 0
      state.username = payload.username || payload.nickname || ""
      state.openid = payload.openid || state.openid || "";
      if (payload.uid) {
        state.isLogin = true;
      } else {
        state.isLogin = false;
      }
      console.log("user in", state.isLogin, state.uid, payload);
    },
    loginApp(state, payload) {
      state.userinfo = payload.userinfo
      state.isloginApp = true;
      console.log("loginApp store")
    },
    socketOpen(state, payload) {
      state.socketOpen = payload.value
      console.log("socketOpen store", state.socketOpen, payload)
    },
    reset(state, payload) {
      state.isLogin = false;
      state.username = '';
      state.uid = '';
      state.openid = "";
      state.amount = 0; //金钱
      state.headimg = "" //用户头像
      state.sid = ""; //socket链接一直存在.可以继续使用.
      state.wsLogin = false;
      state.socketOpen = false;
      console.log("store reset");
    },
  },
  actions: {
    login({ commit }, value) {
      commit({ type: 'login', value: value })
    },
    updateDemoPosition({ commit }, top) {
      commit({ type: 'updateDemoPosition', top: top })
    },
    updateGuidelist({ commit }, guidelist) {
      commit({ type: 'updateGuidelist', guidelist: guidelist })
    },
    setGuideShow({ commit }, value) {
      commit({ type: 'updateGuideShow', guideShow: value })
    },
    openid({ commit }, value) {
      commit({ type: 'openid', openid: value })
    },
    username({ commit }, value) {
      commit({ type: 'username', username: value })
    },
    uid({ commit }, value) {
      commit({ type: 'uid', uid: value })
    },
    amount({ commit }, value) {
      commit({ type: 'amount', amount: value })
    },
    headimg({ commit }, value) {
      commit({ type: 'headimg', headimg: value })
    },
    user({ commit }, value) {
      value.type = 'user';
      commit(value);
      // commit({ type: 'user', user: value })
    }
  }
})


// z39time 
store.registerModule('z39', {
  namespaced: true,
  state: {
    tagitems: [],
    tagitemDic: {},
    sortType: [],
    minDate: "",
    maxDate: "",
    actionCurr: {},
    actionArr: [],
    actionDic: {},
    taskAll: [],
    taskDic: {},
    tagDic: {},
    showMonth: moment().format("YYYY-MM"),
    showYear: moment().format("YYYY"),
    showWeek: moment().format("YYYY 第 WW 周"),
    selectedDayDate: moment().format("YYYY-MM-DD"),
    daysDic: {},
    days: [],
    none: [],
    today: [],
    dayDueChange: false,
    dayGetDic: {},
    projGetDic: {},
    blogGetDic: {},
    projects: [],
    proTasks: [],
    projectPart: [],
    projectPartDic: {},
    tagtmps: [],
    members: [],
    memberDic: {},
    mp3Arr: [],
    mp3Curr: {},
    taskCurr: null,
    filterTaskState: '', //筛选任务状态，0全部，1已完成，2未完成
    projectMode: "default",
    proCurr: null,
    projectAddData: null,
  },
  mutations: {
    usertask(state, payload) {
      state.projects = payload.projs || [];
      state.tagtmps = payload.tagtmps || [];
      state.members = payload.members || [];
      state.minDate = payload.minDate || "";
      state.maxDate = payload.maxDate || "";
      var len = state.members.length;
      for (var i = 0; i <= len - 1; i++) {
        var item = state.members[i];
        state.memberDic["uid_" + item.uid] = item;
      }
      len = state.tagtmps.length;
      for (var i = 0; i <= len - 1; i++) {
        var item = state.tagtmps[i];
        var temp;
        //if (item.pid == 0) {
        if (item.key == 'projectHelp') {
          console.log(item)
          temp = item.tmp.split(',');
          state.projectPartDic[item.pid] = temp;
          state.projectPart = temp;
        }
      }
      store.commit("z39/tagTmpResort");
    },
    membersAdd(state, payload) {
      var len = payload.members.length;
      for (var i = 0; i <= len - 1; i++) {
        var item = payload.members[i];
        state.memberDic["uid_" + item.uid] = item;
      }
    },
    tagSet(state, payload) {
      //let taskdata = payload.task;
      let task = payload.task; // state.taskDic[taskdata.id];
      if (task == undefined) {
        console.log("tag set out");
        return;
      }
      let sdata = payload.sdata;
      let tagitem = {};
      if (!_.isEmpty(task.tags)) {
        Vue.set(task.tags, sdata.key, sdata.value || "");
        //console.log("set tags", task.tags, sdata.key, sdata.value || "", _.clone(task));
      } else {
        tagitem[sdata.key] = sdata.value || "";
        Vue.set(task, "tags", tagitem);
        //console.log("set tags", tagitem);
      }
      console.log(task)
      if (sdata.key == 'due') {
        state.dayDueChange = true;
      }
      let tag = sdata;
      state.tagDic[task.id + "_" + tag.key] = tag;
    },
    tagUpdate(state, payload) {
      let tag = payload.tag;
      let item = state.tagDic[tag.taskid + "_" + tag.key];
      if (item == undefined) {
        state.tagDic[tag.taskid + "_" + tag.key] = tag;
      } else {
        state.tagDic[tag.taskid + "_" + tag.key] = Object.assign(item, tag);
      }
      let task = state.taskDic[tag.taskid];
      if (task == undefined) return console.error("task", tag);
      task.tags[tag.key] = tag.value;
    },
    tagAdd(state, tag) {

    },
    taskSet(state, payload) {
      let task = state.task; // state.taskDic[payload.id];
      if (task) {
        console.log(_.clone(task));
        for (var key in payload) {
          if (key != "type" && key != "task") { // task 没有type字段, type是 commit 中添加的.
            // task[key] = payload[key];
            Vue.set(task, key, payload[key]);
          }
        }
        console.log(_.clone(task));
      }
    },
    taskToDB(state, payload) {
      let tasks = payload.tasks;
      let type = payload.act;
      var len = tasks ? tasks.length : 0,
        taskIndex, tag, tags;
      let override = payload.override || false;
      console.log(payload)
      if (type == "add") {
        for (var i = 0; i <= len - 1; i++) {
          var task = tasks[i];
          if (task == undefined) continue;
          task.tagsArr = task.tags = task.tags || [];
          var tag, tags;
          task.state == 'done' ? task.finished = true : task.finished = false; //任务是否完成
          if (task.tags && task.tags instanceof Array) {
            tags = {};
            for (var k in task.tags) {
              tag = task.tags[k];
              if (tag == undefined) { continue; }
              if (tags[tag.key] == undefined) {
                tags[tag.key] = tag.value;
              } else { //现在只有toggle 是重复的.
                tags[tag.key] = tags[tag.key] > tag.value ? tags[tag.key] : tag.value; //只有暂停是重复,且在导出为tlog才会用到.
                // tags[tag.key] += " " + tag.value;
              }
              if (state.tagDic[task.id + "_" + tag.key] == undefined || override) {
                state.tagDic[task.id + "_" + tag.key] = tag;
              }
            }
            task.tags = tags;
          }
        }
      }
      for (i = 0; i <= len - 1; i++) {
        var task = tasks[i];
        if (task == undefined) continue;
        if (type == "add") {
          if (state.taskDic[task.id] == undefined) {
            // state.taskAll.splice(0, 0, task);
            state.taskAll.unshift(task);
            Vue.set(state.taskDic, task.id, task);
          }
          if (state.taskDic[task.id] == undefined) {
            state.taskDic[task.id] = task;
          }
          // console.error("task:", _.clone(task), _.clone(state.taskDic[task.id]));
        } else if (type == "del") {
          if (state.taskDic[task.id] != undefined) {
            delete state.taskDic[task.id];
            taskIndex = state.taskAll.indexOf(task);
            if (taskIndex > -1) {
              state.taskAll.splice(taskIndex, 1);
            }
          }
        }
      }
      // console.log("len ", type, len, state.taskAll.length, tasks, state.taskAll);
    },
    projectAdd(state, payload) {
      state.projects.push(payload.project);
    },
    projectDel(state, payload) {
      var len = state.projects.length;
      for (var i = 0; i <= len - 1; i++) {
        var item = state.projects[i];
        if (item.id == payload.id) {
          state.projects.splice(i, 1);
          break;
        }
      }
    },
    projectSet(state, payload) {
      var len = state.projects.length;
      for (var i = 0; i <= len - 1; i++) {
        var item = state.projects[i];
        if (item.id == payload.project.id) {
          _.extend(item, payload.project);
          break;
        }
      }
    },
    tagitems(state, payload) {
      state.tagitems = payload.tagitems;
      var len = payload.tagitems.length;
      var temp = {};
      for (var i = 0; i <= len - 1; i++) {
        var item = payload.tagitems[i];
        temp[item.key] = item.name;
      }
      state.tagitemDic = temp;
    },
    tagitemsAdd(state, payload) {
      state.tagitems = state.tagitems.concat(payload.tagitems);
      var len = payload.tagitems.length;
      for (var i = 0; i <= len - 1; i++) {
        var item = payload.tagitems[i];
        state.tagitemDic[item.key] = item.name;
      }
    },
    actionCurr(state, payload) {
      state.actionCurr = payload;
    },
    actionAdd(state, payload) {
      if (state.actionDic[payload.id] != undefined) {
        return; //已经有了此数据
      }
      state.actionDic[payload.id] = payload;
      state.actionArr.unshift(payload);
    },
    actionSet(state, payload) {
      var temp = []; // state.actionArr; //.concat(payload.acts);
      var acts = payload.acts;
      var len = acts.length;
      for (var i = 0; i <= len - 1; i++) {
        var item = acts[i];
        if (state.actionDic[item.id] == undefined) {
          temp.push(item);
          state.actionDic[item.id] = item;
        }
      }
      temp = state.actionArr.concat(temp);
      console.log(temp);
      state.actionArr = temp;
    },
    sortType(state, payload) {
      state.sortType = payload.sorts;
    },
    daysDic(state, payload) {
      let month = payload.month;
      let days = [];
      if (payload.days) {
        state.daysDic[month] = payload.days;
        days = payload.days;
        state.days = days;
        // Vue.set(state.daysDic, month, payload.days);   使用days后 不再需要daysdic更新.
      } else if (payload.day) {
        let day = payload.day;
        month = day.match(/(\d\d\d\d-\d\d)/)[0];
        if (state.daysDic[month] != undefined && state.daysDic[month].length > 0) {
          days = state.daysDic[month];
          // days = _.clone(days);
          // console.log("daysDic  store day ", days, day);
          let monthCurr = state.showMonth;
          if (days.indexOf(day) == -1) {
            days.push(day);
            days = days.sort();
            if (monthCurr == month) { //如果是当前月,则更新days 列表.
              state.days = days;
            }
          }
        } else {
          days = [day];
          state.daysDic[month] = [day];
        }
        if (day > state.maxDate) {
          state.maxDate = day;
        }
      }
      // 需要判断是否当前选择月份,如果是则跟新日期.
      // console.log("daysDic  store", days);
    },
    showMonth(state, payload) {
      state.showMonth = payload.value;
    },
    changeDate(state, payload) {
      if (payload.dateType == 'year') {
        state.showMonth = moment(state.showMonth).set('year', payload.value).format('YYYY-MM');
        state.showYear = payload.value;
        state.selectedDayDate = state.showMonth + '-' + moment(state.selectedDayDate).format('DD');
      } else if (payload.dateType == 'month') {
        state.showMonth = payload.value;
        state.selectedDayDate = payload.value + '-' + moment(state.selectedDayDate).format('DD');
        state.showYear = moment(payload.value).format('YYYY');
      } else if (payload.dateType == 'week') {
        state.showWeek = payload.value;
      } else if (payload.dateType == 'day') {
        state.selectedDayDate = state.showMonth + '-' + (payload.value.length > 1 ? payload.value : ("0" + payload.value));
      }
    },
    deleteTagTmp(state, payload) {
      state.tagtmps.forEach((item, index, arr) => {
        if (item.id == payload.id) {
          arr.splice(index, 1)
        }
      })
    },
    mp3Arr(state, payload) {
      state.mp3Arr = payload.mp3Arr;
      // console.log("mp3Arr", state.mp3Arr);
    },
    mp3Update(state, payload) { //上传音频后更新状态
      Vue.set(state, "mp3Update", payload.mp3item);
    },
    mp3Curr(state, payload) {
      state.mp3Curr = payload.mp3Curr;
      // console.log("mp3Curr", state.mp3Curr);
    },
    mp3Add(state, payload) {
      state.mp3Curr = payload.mp3Curr;
    },
    dayDueChange(state, payload) {
      state.dayDueChange = payload.dayDueChange;
    },
    taskCurr(state, payload) {
      state.taskCurr = payload.task;
      // console.log("store taskCurr", state.taskCurr);
    },
    reset(state, payload) {
      // state.tagitems = [];
      // state.tagitemDic = {};
      state.sortType = [];
      // state.minDate = "";
      // state.maxDate = "";
      state.actionCurr = {};
      state.actionArr = [];
      state.actionDic = {};
      state.taskAll = [];
      state.taskDic = {};
      state.tagDic = {};
      // state.showMonth = "";
      state.daysDic = {};
      state.days = [];
      state.dayDueChange = false;
      state.dayGetDic = {};
      state.projGetDic = {};
      state.blogGetDic = {};
      state.projects = [];
      state.proTasks = [];
      state.tagtmps = [];
      state.members = [];
      state.mp3Arr = [];
      state.mp3Curr = {};
      state.mp3Update = {};
      state.taskCurr = null;
    },
    updateTagTmps(state, payload) {
      state.tagtmps.forEach(function(item, index, arr) {
        if (item.key == payload.key) {
          item.id = payload.id;
          item.tmp = payload.tmp;
          item.init = null;
        }
      })
    },
    addTagTmps(state, payload) {
      delete payload.type;
      state.tagtmps.push(payload)
    },
    setFilterState(state, payload) {
      state.filterTaskState = payload.state;
    },
    tagTmpResort(state) {
      //使用本地缓存的标签模板顺序
      var tagArr = JSON.parse(localStorage.getItem('tagTmpSortArr'));
      var originalArr = Object.assign([], state.tagtmps)
      if (tagArr) {
        var resortArr = [];
        for (var i = 0; i < tagArr.length; i++) {
          for (var j = 0; j < originalArr.length; j++) {
            if (originalArr[j].key == tagArr[i]) {
              resortArr.push(originalArr[j])
              originalArr.splice(j, 1)
            }
          }
        }
        state.tagtmps = resortArr.concat(originalArr);
      }
    },
    projectMode(state, payload) {
      state.projectMode = payload.projectMode;
    },
    proCurr(state, payload) {
      state.proCurr = payload.project;
    },
    projectAddData(state, payload) {
      state.projectAddData = payload.project;
    },

  }
});


// z43phone 项目编号
store.registerModule('z43', {
  namespaced: true,
  state: {
    gid: 0,
    dutyon: "",
    dutyoff: "",
    gname: "",
    gdesc: "",
    timeend: '2017-06-01',
    gfriends: '',
    gfrilist: [],
    masters: '',
    gmp3s: [],
    gimgs: [],
    groupDic: {},
    peoples: [], //通讯录列表的数据(联系人);
    currMembers: [],
    addMembers: [],
  },
  mutations: {
    setGroup(state, payload) {
      state.gid = payload.id;
      state.dutyon = parseInt(payload.dutyon);
      state.dutyoff = parseInt(payload.dutyoff);
      state.gname = payload.name;
      state.gdesc = payload.desc;
      state.timeend = payload.timeend;
      state.masters = payload.masters;
      // state.gmp3s = payload.mp3s;
      state.gimgs = payload.imgs;
      if (!state.groupDic[payload.id]) {
        state.groupDic[payload.id] = payload;
      }
      state.gfrilist = payload.friends;
      if (payload.mp3s && payload.mp3s.count) {
        state.gmp3s = payload.mp3s.data;
      } else {
        state.gmp3s = [];
      }
    },
    setGroupId(state, payload) {
      state.gid = payload;
    },
    setPeoples(state, payload) {
      state.peoples = payload;
    },
    addMembers(state, payload) {
      state.addMembers = payload.list;
    },
    currMembers(state, payload) {
      state.currMembers = payload.list;
    }
  }
});
export default store;
